<template>
  <el-card class="list-page" @click="handleDeptList(false)">
    <el-form
      :inline="true"
      :model="formInline"
      :label-position="'right'"
      ref="formRef"
      class="demo-form-inline"
      :label-width="'130px'"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="合同编号/名称" prop="sectionNameLike">
            <el-input
              v-model="formInline.sectionNameLike"
              placeholder="合同编号/名称"
              @change="handleSearch"
              class="width-custom"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同类型" prop="sectionType">
            <el-select
              v-model="formInline.sectionType"
              placeholder="合同类型"
              @change="handleSearch"
              class="width-custom"
              clearable
            >
              <el-option
                class="default-option"
                v-for="item in sectionTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" prop="projectNameLike">
            <el-input
              v-model="formInline.projectNameLike"
              placeholder="项目名称"
              class="width-custom"
              @change="handleSearch"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目类型" prop="projectTypeCode">
            <el-select
              v-model="formInline.projectTypeCode"
              placeholder="项目类型"
              @change="handleSearch"
              class="width-custom"
              clearable
            >
              <el-option
                class="default-option"
                v-for="item in projectTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目所属片区/单位">
            <el-input
              clearable
              placeholder="项目所属片区/单位"
              v-model.trim="filterText"
              @clear="clearInput"
              class="width-custom"
              @click.stop="handleDeptList(true)"
            ></el-input>
            <el-tree
              clearable
              ref="treeRef"
              class="filter-tree"
              :data="deptList"
              default-expand-all
              :props="defaultProps"
              :filter-node-method="filterNode"
              v-if="showDeptList"
              @node-click="handleChangeDept"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目年度" prop="projectYear">
            <el-date-picker
              v-model="formInline.projectYear"
              type="year"
              value-format="YYYY"
              placeholder="项目年度"
              class="width-custom"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同创建人" prop="createUserNameLike">
            <el-input
              v-model="formInline.createUserNameLike"
              placeholder="合同创建人"
              @change="handleSearch"
              class="width-custom"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同实施进度" prop="contractProgressCode">
            <el-select
              v-model="formInline.contractProgressCode"
              placeholder="合同实施进度"
              @change="handleSearch"
              class="width-custom"
              clearable
            >
              <el-option
                class="default-option"
                v-for="item in progressList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="合同签订日期" prop="signDate">
            <el-date-picker
              v-model="formInline.signDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              @change="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item style="float: right">
            <el-button
              type="primary"
              @click="exportFunc"
              v-auth="`/projects/section--export`"
              >导出</el-button
            >
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-skeleton
      style="height: calc(100vh - 400px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="tableData"
      stripe
      v-show="!loading"
      style="width: 100%; margin-top: 20px"
      :height="'calc(100vh - 400px)'"
      row-key="id"
      ref="tableRef"
      @selection-change="selectionChange"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>
      <el-table-column type="selection" :reserve-selection="true" width="35" />
      <el-table-column type="index" label="序号" width="50" fixed="left">
        <template v-slot="scope">
          <span>{{
            (formInline.pageNum - 1) * formInline.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="sectionCode"
        label="合同编号"
        width="180"
        fixed="left"
      ></el-table-column>
      <el-table-column label="合同名称" width="180" fixed="left">
        <template #default="{ row }">
          <el-tooltip
            class="box-item"
            placement="bottom-end"
            popper-class="tooltip-popper"
          >
            <template #content>
              <div style="max-width: 260px; line-height: 18px">
                {{ row.sectionName }}
              </div>
            </template>
            <el-button
              type="text"
              class="shot-text"
              @click="lookMonomer(row)"
              >{{ row.sectionName }}</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" width="240">
        <template #default="{ row }">
          <el-tooltip
            class="box-item"
            placement="bottom-end"
            popper-class="tooltip-popper"
          >
            <template #content>
              <div style="max-width: 260px; line-height: 18px">
                {{ row.projectName }}
              </div>
            </template>
            <el-button
              type="text"
              class="shot-text"
              @click="handleOperate(row)"
              >{{ row.projectName }}</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        prop="projectCode"
        label="项目编号"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="projectRegionName"
        label="项目所属区域"
        width="150"
      ></el-table-column>
      <el-table-column
        prop="projectFactoryName"
        label="项目所属单位"
        width="150"
      ></el-table-column>
      <el-table-column label="项目年度" width="80">
        <template #default="{ row }">
          <span>{{ row.projectYear }}年</span>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" width="80">
        <template #default="{ row }">
          <span>{{ projectTypeObj[row.projectTypeCode] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同类型" width="80">
        <template #default="{ row }">
          <span>{{ sectionTypeObj[row.sectionType] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="contractProgressName"
        label="合同实施进度"
        width="160"
      >
      </el-table-column>
      <el-table-column
        prop="contractAmount"
        width="160"
        label="合同金额（含税，元）"
      ></el-table-column>
      <el-table-column
        prop="currencyAmountNoTax"
        width="180"
        label="合同金额（不含税，元）"
      ></el-table-column>
      <el-table-column
        prop="signDate"
        label="合同签订日期"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="createUserName"
        label="合同创建人"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="合同创建时间"
        width="160"
      ></el-table-column>
    </el-table>
    <re-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="formInline.pageNum"
      v-model:limit="formInline.pageSize"
      @pagination="handleSearch(formInline.pageNum)"
    />
  </el-card>
</template>

<script lang="ts">
import { reactive, toRefs, ref, defineComponent, onMounted } from "vue";
import { useRouter } from "vue-router";
import RePagination from "/@/components/RePagination/index.vue";
import { allSectionList, getDeptTree } from "/@/api/projects";
import { storageLocal } from "/@/utils/storage";
import { postDictList } from "/@/api/home";
import { exportExcel } from "/@/utils/file";
export default defineComponent({
  name: "section",
  components: {
    RePagination
  },
  setup() {
    let router = useRouter();
    const formRef = ref<HTMLFormElement | null>(null) as any;
    let loading = ref<boolean>(false);
    let total = ref<number>(0);
    let formInline = reactive({
      pageNum: 1,
      pageSize: 10,
      sectionNameLike: "",
      sectionType: "",
      projectNameLike: "",
      projectTypeCode: "",
      createUserNameLike: "",
      contractProgressCode: "",
      signDate: [],
      projectRegionCode: "",
      projectYear: ""
    });
    let sectionTypeList = ref([]);
    let sectionTypeObj = ref({});
    let projectTypeList = ref([]);
    let projectTypeObj = ref({});
    let progressList = ref([]);
    let progressObj = ref({});
    let selectRows = ref([]);
    let filterText = ref("");
    const deptList = ref([]);
    let defaultProps = ref({
      children: "children",
      label: "deptDescShrt"
    });
    let showDeptList = ref(false);

    let state = reactive({
      tableData: []
    }) as any;

    onMounted(() => {
      initSectionTypeList();
      initProjectTypeList();
      getSelectData();
      getTableData(formInline);
      getDeptTreeFunc();
    });

    // 工厂区域
    const getDeptTreeFunc = async () => {
      try {
        const { data } = await getDeptTree({});
        deptList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };

    // 合同类型
    const initSectionTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_sec_con_type" });
        sectionTypeList.value = data || [];
        sectionTypeList.value.forEach(item => {
          sectionTypeObj.value[item.dicCode] = item.dicValue;
        });
      } catch (err) {
        console.log(err);
      }
    };
    // 项目类型
    const initProjectTypeList = async () => {
      try {
        postDictList({ dicType: "thd_pro_type" }).then((res: any) => {
          const { data } = res;
          projectTypeList.value = (data || []).map((val: any) => {
            projectTypeObj.value[val.dicCode] = val.dicValue;
            return {
              ...val
            };
          });
        });
      } catch (err) {
        console.log(err);
      }
    };
    // 获取实施进度
    const getSelectData = async () => {
      try {
        const { data } = await postDictList({
          dicType: "contract_progress_type"
        });
        progressList.value = (data || []).map((val: any) => {
          progressObj.value[val.dicCode] = val.dicValue;
          return {
            ...val
          };
        });
      } catch (error) {
        console.log(error);
      }
    };

    // 重置条件
    const handleReset = (): void => {
      formRef.value.resetFields();
      formInline.projectRegionCode = "";
      filterText.value = "";
      getTableData(formInline);
    };

    // 根据条件进行搜索
    const handleSearch = (page?: any) => {
      if (!page) {
        formInline.pageNum = 1;
      }
      getTableData(formInline);
    };

    //获取单体列表
    const getTableData = async (obj: any) => {
      const { signDate } = obj;
      loading.value = true;
      try {
        let signDateStart = "";
        let signDateEnd = "";
        if (signDate && signDate.length > 0) {
          signDateStart = signDate[0];
          signDateEnd = signDate[1];
        }
        const { code, data } = await allSectionList({
          ...obj,
          signDateStart,
          signDateEnd
        });
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    };

    const handleOperate = (row: any) => {
      ["A", "B"].includes(row.projectTypeCode)
        ? router.push(`/projects${row.projectTypeCode}`)
        : row.projectTypeCode == "S"
        ? router.push(`/projectsB/manage/archives`)
        : router.push(`/projectsA`);
      storageLocal.removeItem("sectionInfo");
      storageLocal.setItem("projectInfo", {
        ...row,
        id: row.projectId,
        name: row.projectName,
        typeCode: row.projectTypeCode,
        typeName: row.projectTypeName,
        leaderId: row.projectLeaderId,
        leaderName: row.projectLeaderName
      });
    };

    const lookMonomer = (row: any) => {
      storageLocal.setItem("projectInfo", {
        ...row,
        id: row.projectId,
        name: row.projectName,
        typeCode: row.projectTypeCode,
        typeName: row.projectTypeName,
        leaderId: row.projectLeaderId,
        leaderName: row.projectLeaderName
      });
      storageLocal.setItem("sectionInfo", {
        id: row.id,
        name: row.sectionName,
        leaderId: row.leaderId,
        leaderName: row.leaderName,
        sectionType: row.sectionType,
        startWorkId: row.startWorkId,
        startWorkStatus: row.startWorkStatus,
        sectionName: row.sectionName,
        sectionCode: row.sectionCode
      });
      if (row.sectionType == 4) {
        router.push({ path: "/projectsS/document/engineering" });
      } else {
        router.push({ path: "/projectsS" });
      }
    };
    const selectionChange = (rows: any) => {
      selectRows.value = rows;
    };
    const exportFunc = () => {
      const arr = selectRows.value.map(val => val.id);
      let formData: any = null;
      if (arr.length === 0) {
        formData = {
          ...formInline,
          pageNum: 1,
          pageSize: 0
        };
      } else {
        formData = {
          sectionIds: arr,
          pageNum: 1,
          pageSize: 0
        };
      }
      exportExcel(
        "/snow-admin/projectSection/exportAllSection",
        formData,
        `合同列表`
      );
    };
    const clearInput = () => {
      formInline.projectRegionCode = "";
    };

    const handleDeptList = flag => {
      showDeptList.value = flag;
    };
    const filterNode = (value: string, data) => {
      if (!value) return true;
      return data.deptDescShrt.includes(value);
    };

    const handleChangeDept = node => {
      formInline.projectRegionCode = node.id;
      filterText.value = node.deptDescShrt;
      showDeptList.value = false;
    };

    return {
      ...toRefs(state),
      total,
      formRef,
      loading,
      formInline,
      sectionTypeList,
      sectionTypeObj,
      progressList,
      progressObj,
      projectTypeList,
      projectTypeObj,
      selectRows,
      filterText,
      deptList,
      defaultProps,
      showDeptList,
      handleReset,
      handleSearch,
      lookMonomer,
      handleOperate,
      selectionChange,
      exportFunc,
      clearInput,
      handleDeptList,
      getDeptTreeFunc,
      filterNode,
      handleChangeDept
    };
  }
});
</script>
<style>
.el-icon-warning {
  color: #e45d5d !important;
}
.width-custom {
  width: 170px !important;
}
</style>
<style lang="scss" scoped>
.shot-text {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -webkit-line-clamp: 1;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  white-space: nowrap;
}
.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 36px;
    width: 400px;
    max-height: 226px;
    overflow: auto;
    border: 1px solid #e4e8f2;
    z-index: 10;
  }
}
</style>
